package mars.ns.selectors

import mars.ns.core._
import scala.util.Random
import dummy.world.Family

/**
 * This trait selects random nodes and connects random nodes
 */
trait DepthFirstSelection[T <: Node] extends RandomSelection[T] {
    var nodesToSelect : List[T] = List[T]()
    var selectedNodes : List[T] = List[T]()    
	override def selectNode(network: Network[T]): T = {
      	if(nodesToSelect.isEmpty){
      		this.nodesToSelect ::= super.selectNode(network)
      		if(selectedNodes.length == network.getNodes().length){
      			this.selectedNodes = List[T]()
      		}
      	}
      	val selected : T = this.nodesToSelect.head
      	selected.getLinkedObjects().foreach(linked => (linked match{case l:T => if(selectedNodes exists (linked==)){this.nodesToSelect ::= l;this.selectedNodes ::= l}}) )
      	this.nodesToSelect = this.nodesToSelect remove (selected==)
        return selected
    }
    
    override def connect(network: Network[T], node: T) :Set[Link] ={
		if(this.avoidRecursion == MAX_RECURSION){
			throw new Error("Couldn't connect two nodes in the resting network");
		}
        var node2 = super.selectNode(network)
        if(node.getLinksTo(node2).size > 0)
        {
        	this.avoidRecursion +=1
			connect(network,node)
        }
        node.addDoubleLink(node2, new DefaultLink)
        return node.getLinksTo(node2)
    }
}